package cn.fintecher.pangolin.service.dataimp.task;

import cn.fintecher.pangolin.common.enums.*;
import cn.fintecher.pangolin.common.model.UserModel;
import cn.fintecher.pangolin.common.utils.BeanUtils;
import cn.fintecher.pangolin.common.utils.ZWDateUtil;
import cn.fintecher.pangolin.entity.elastic.BaseCase;
import cn.fintecher.pangolin.entity.elastic.CaseTransferLog;
import cn.fintecher.pangolin.entity.elastic.DistributeModel;
import cn.fintecher.pangolin.entity.mysql.CaseInfo;
import cn.fintecher.pangolin.entity.mysql.QCaseInfo;
import cn.fintecher.pangolin.entity.mysql.QUser;
import cn.fintecher.pangolin.entity.mysql.User;
import cn.fintecher.pangolin.service.dataimp.elastic.BaseCaseElastic;
import cn.fintecher.pangolin.service.dataimp.model.ConfirmCommonModel;
import cn.fintecher.pangolin.service.dataimp.model.DistributeConfirmModel;
import cn.fintecher.pangolin.service.dataimp.repository.CaseInfoRepository;
import cn.fintecher.pangolin.service.dataimp.repository.UserRepository;
import cn.fintecher.pangolin.service.dataimp.service.BaseService;
import org.apache.commons.collections4.IterableUtils;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.CompletableFuture;

/**
 * @Auther: xiaqun
 * @Description:
 * @Date: 15:22 2019/11/5
 */

@Service("confirmDistributeFuture")
public class ConfirmDistributeFuture {

    @Autowired
    private BaseCaseElastic baseCaseElastic;

    @Autowired
    private CaseInfoRepository caseInfoRepository;

    @Autowired
    private BaseService baseService;

    @Autowired
    private UserRepository userRepository;

    /**
     * 多线程确认
     */
    @Async
    public CompletableFuture<DistributeConfirmModel> processDistribute(List<DistributeModel> list, UserModel userModel) {
        DistributeConfirmModel distributeConfirmModel = new DistributeConfirmModel();
        List<BaseCase> baseCases = new ArrayList<>();
        List<CaseInfo> caseInfos = new ArrayList<>();
        List<CaseTransferLog> caseTransferLogs = new ArrayList<>();
        List<DistributeModel> distributeModels = new ArrayList<>();
        List<String> errors = new ArrayList<>();
        List<String> caseNumbers = new ArrayList<>();
        List<String> userNames = new ArrayList<>();
        for (DistributeModel model : list) {
            caseNumbers.add(model.getCaseNumber());
            userNames.add(model.getUsername());
        }
        BoolQueryBuilder builder = new BoolQueryBuilder();
        builder.must(QueryBuilders.termsQuery("caseNumber.keyword", caseNumbers));
        Iterable<BaseCase> baseCaseIterable = baseCaseElastic.search(builder);
        Iterable<CaseInfo> caseInfoIterable = caseInfoRepository.findAll(QCaseInfo.caseInfo.caseNumber.in(caseNumbers));
        Iterable<User> userIterable = userRepository.findAll(QUser.user.username.in(userNames));
        List<BaseCase> baseCaseList = IterableUtils.toList(baseCaseIterable);
        List<CaseInfo> caseInfoList = IterableUtils.toList(caseInfoIterable);
        List<User> userList = IterableUtils.toList(userIterable);
        Map<String, ConfirmCommonModel> map = new HashMap<>();
        for (DistributeModel model : list) {
            ConfirmCommonModel confirmCommonModel = new ConfirmCommonModel();
            confirmCommonModel.setUserName(model.getUsername());
            confirmCommonModel.setDistributeModel(model);
            for (BaseCase baseCase : baseCaseList) {
                if (model.getCaseNumber().equals(baseCase.getCaseNumber())) {
                    confirmCommonModel.setBaseCase(baseCase);
                    break;
                }
            }
            for (CaseInfo caseInfo : caseInfoList) {
                if (model.getCaseNumber().equals(caseInfo.getCaseNumber())) {
                    confirmCommonModel.setCaseInfo(caseInfo);
                    break;
                }
            }
            for (User user : userList) {
                if (model.getUsername().equals(user.getUsername())) {
                    confirmCommonModel.setUser(user);
                    break;
                }
            }
            map.put(model.getCaseNumber(), confirmCommonModel);
        }
        for (Map.Entry<String, ConfirmCommonModel> entry : map.entrySet()) {
            ConfirmCommonModel confirmCommonModel = entry.getValue();
            DistributeModel distributeModel = confirmCommonModel.getDistributeModel();
            BaseCase baseCase = confirmCommonModel.getBaseCase();
            CaseInfo caseInfo = confirmCommonModel.getCaseInfo();
            User user = confirmCommonModel.getUser();
            if (Objects.isNull(user)) {
                errors.add("员工工号为【" + confirmCommonModel.getUserName() + "】的用户不存在");
                break;
            }
            if (user.getStatus().equals(UserStatus.LEAVE)) {
                errors.add("员工工号为【" + user.getUsername() + "】的用户已离职");
                break;
            }
            if (Objects.nonNull(caseInfo)) {
                if (Objects.nonNull(caseInfo.getCurrentCollector())) {
                    errors.add("案件编号为【" + caseInfo.getCaseNumber() + "】的案件已经分配");
                    break;
                }
                caseInfo.setDepartment(null);
                caseInfo.setCaseType(Objects.nonNull(caseInfo.getCaseType()) ? caseInfo.getCaseType() : CaseType.TEL_CASE);
                caseInfo.setCaseDataStatus(CaseDataStatus.IN_POOL);
                caseInfo.setPublicCaseFlag(PublicCaseFlag.NO_PUBLIC_CASE);
            } else {
                caseInfo = new CaseInfo();
                caseInfo.setCaseType(CaseType.TEL_CASE);
                BeanUtils.copyPropertiesIgnoreNull(baseCase, caseInfo);
                caseInfo.setAddress(baseCase.getHomeAddr());
                caseInfo.setIsAssist(BaseSelect.NO);
            }
            String outUserId = caseInfo.getCurrentCollector().getId();
            caseInfo.setCurrentCollector(user);
            caseInfo.setTransferDate(ZWDateUtil.getNowDateTime());
            caseInfo.setOperator(userModel.getRealName());
            caseInfo.setOperatorTime(ZWDateUtil.getNowDateTime());
            baseCase.setIsDistribute(BaseSelect.YES);
            baseCases.add(baseCase);
            caseTransferLogs.add(baseService.createCaseTranferLog(baseCase.getId(), "案件流转:".concat(user.getRealName()), userModel, outUserId, user.getId(), baseCase.getLeftAmt()));
            caseInfos.add(caseInfo);
            distributeModel.setFlag(1);
            distributeModels.add(distributeModel);
        }
        distributeConfirmModel.setBaseCases(baseCases);
        distributeConfirmModel.setCaseInfos(caseInfos);
        distributeConfirmModel.setCaseTransferLogs(caseTransferLogs);
        distributeConfirmModel.setDistributeModels(distributeModels);
        distributeConfirmModel.setErrors(errors);
        return CompletableFuture.completedFuture(distributeConfirmModel);
    }
}
